package com.limou.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.limou.pojo.User;
import com.limou.pojo.UserQueryDTO;
import com.limou.pojo.common.res.ResultData;
import com.limou.service.UserService;
import com.limou.utils.RandomCode;
import com.limou.utils.SendMail;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.ValidationException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    // 登录的图形验证码
    private String code;

    @Autowired
    private UserService userService;

    /**
     * 检查登录
     * @param user
     * @param code
     * @return
     */
    @RequestMapping("/checkLogin")
    public ModelAndView checkLogin(User user, String code) {
        // 通过前端传入的用户名密码到数据库查询出的userByMapper
        User userByMapper = userService.checkLogin(user);

        System.out.println("前端图片验证码结果：" + this.code);
        System.out.println("自己输入结果：" + code);

        ModelAndView modelAndView = new ModelAndView();

        // 用户名密码正确，跳转到登录页面
        if (userByMapper != null && this.code.equals(code)) {

            modelAndView.setViewName("index");
            modelAndView.addObject("user", userByMapper);
            // 跳转到登录首页
            return modelAndView;
        } else {
            // 用户名密码验证码不正确
//            modelAndView.setViewName("redirect:/welcome.jsp");
            modelAndView.addObject("msg", "检查您输入信息是否有误");
            modelAndView.setViewName("login");
            return modelAndView;
        }
    }


    /**
     * 登录验证码
     * 这个方法是为了生成验证码图片 和 运算结果
     * @param response
     * @throws Exception
     */
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response) throws Exception {

        ServletOutputStream outputStream = response.getOutputStream();

        // 算数验证🐎
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 32);

        // 参数表示几位数运算
        captcha.setLen(2);

        // 算术
        System.out.println(captcha.getArithmeticString()); // eg； 3 + 2 = ？

        // 获取运算结果
        String result = captcha.text();

        this.code = result;
        System.out.println(result);

        captcha.out(outputStream);
    }


    /**
     * 注册
     * @param user
     * @param emailCode 前端输入的邮箱验证码
     * @return
     */
    @RequestMapping("/register")
    public ModelAndView register(User user, String emailCode) {
        // 如果邮箱验证码正确跳转到登录页面
        if(this.randomEmailCode.equals(emailCode)){
            // 添加用户
            userService.register(user);

            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("login");
            return modelAndView;
        }else {
            // 邮箱验证码不正确
            ModelAndView modelAndView = new ModelAndView();

            modelAndView.addObject("msg_code","您输入的邮箱验证码有误");
            modelAndView.setViewName("register");
            return modelAndView;
        }

    }

    // 随机生成的邮件验证码（工具类）
    private String randomEmailCode;

    /**
     * 发送邮件验证码
     * @param email
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendEmailCode")
    public String sendEmailCode(String email) {
        System.out.println("前台输入的邮箱是：" + email);

        // 实例化一个发送邮件的对象
        SendMail mySendMail = new SendMail();

        String randomEmailCode = RandomCode.generateNum(6);
        // 同时将生成的随机验证码赋值给全局变量
        this.randomEmailCode = randomEmailCode;
        System.out.println("随机邮箱验证码是：" + this.randomEmailCode);

        // 发送邮件
        mySendMail.sendMail(email, "随机生成的验证码是" + randomEmailCode + "，抓紧时间搞快点输入");

        return "true";
    }

    /**
     * Ajax实现页面异步刷新，检测用户名是否重复
     * @param username
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkUsernameRepeat")
    public String checkUsernameRepeat(String username) {
        User user = userService.queryUserByUsername(username);

        if (user == null) {
            return "false";
        } else {
            return "true";
        }
    }


    //用户页面
    @GetMapping("/page")
    public String page(){
        return "user";
    }


    //新增
    @ResponseBody
    @RequestMapping(value ="/insert",produces={"text/html;charset=UTF-8"})
    public String insert(User user){
        ResultData rc = new ResultData();
        try {
            rc.setData(userService.insert(user));
        } catch (ValidationException e) {
            rc.setError(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            rc.setErrorMsg(e.getMessage());
            e.printStackTrace();
        }
        return JSON.toJSONString(rc);
    }

    //删除
    @ResponseBody
    @DeleteMapping(value ="/delete",produces={"text/html;charset=UTF-8"})
    public String delete(@RequestParam Integer id){
        ResultData rc = new ResultData();
        try {
            rc.setData(userService.delete(id));
        } catch (ValidationException e) {
            rc.setError(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            rc.setErrorMsg(e.getMessage());
            e.printStackTrace();
        }
        return JSON.toJSONString(rc);
    }

    //更新
    @ResponseBody
    @RequestMapping(value ="/update",produces={"text/html;charset=UTF-8"})
    public String update(User user){
        ResultData rc = new ResultData();
        try {
            rc.setData(userService.updateData(user));
        } catch (ValidationException e) {
            rc.setError(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            rc.setErrorMsg(e.getMessage());
            e.printStackTrace();
        }
        return JSON.toJSONString(rc);
    }

    //查询分页数据
    @ResponseBody
    @GetMapping(value = "/list",produces={"text/html;charset=UTF-8"})
    public String getList(UserQueryDTO dto){
        ResultData rc = new ResultData();
        try {
            PageHelper.startPage(dto.getPage(), dto.getSize());
            List<User> list = userService.getList(dto);
            PageInfo<User> data = new PageInfo<>(list);
            rc.setData(data);
        } catch (ValidationException e) {
            rc.setError(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            rc.setErrorMsg(e.getMessage());
            e.printStackTrace();
        }
        return JSON.toJSONString(rc);
    }


}
